package org.linlinjava.litemall.web.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallCashSchedule;
import org.linlinjava.litemall.db.domain.LitemallCashSettlement;
import org.linlinjava.litemall.db.service.LitemallCashScheduleService;
import org.linlinjava.litemall.db.service.LitemallCashSettlementService;
import org.linlinjava.litemall.web.dto.WebCashSettlementDTO;
import org.linlinjava.litemall.web.vo.WebPosGetOffVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class WebCashSettlementService {

    private final LitemallCashSettlementService cashSettlementService;

    private final LitemallCashScheduleService cashScheduleService;


    public ResponseUtil.Response enteringCashSettlement(WebCashSettlementDTO cashSettlementDTO, Integer userId, Integer shopId) {
        if(ObjectUtil.isNull(cashSettlementDTO)){return ResponseUtil.badArgument();}
        LitemallCashSettlement cashSettlement = LitemallCashSettlement.builder()
                .userId(userId)
                .shopId(shopId)
                .addTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .deleted(false)
                .build();
        BeanUtils.copyProperties(cashSettlementDTO,cashSettlement);

        return cashSettlementService.save(cashSettlement)?ResponseUtil.ok():ResponseUtil.fail();
    }
    static List<LitemallCashSettlement.Denomination> parseJsonData(String jsonData) {
        List<LitemallCashSettlement.Denomination> items = new ArrayList<>();

        // 移除字符串中的首尾方括号
        jsonData = jsonData.substring(1, jsonData.length() - 1);

        // 按逗号分隔字符串得到每个数据项
        String[] dataItems = jsonData.split(",");

        // 遍历每个数据项，解析价格和数量
        for (String item : dataItems) {
            String[] keyValue = item.split(":");

            String priceString = keyValue[0].trim();
            double price = Double.parseDouble(priceString.substring(priceString.indexOf(":") + 1));

            String numberString = keyValue[1].trim();
            int number = Integer.parseInt(numberString.substring(numberString.indexOf(":") + 1));
            items.add(new LitemallCashSettlement.Denomination(new BigDecimal(price), number));
        }

        return items;
    }


    public ResponseUtil.Response gotOff(Integer userId, Integer shopId,String deviceNo) {
        if(userId==null){
            return ResponseUtil.badArgument();
        }
        //当前设备 当天 当前门店 当前店员
        List<LitemallCashSchedule> cashSchedules = cashScheduleService.list(Wrappers.lambdaQuery(LitemallCashSchedule.class)
                .eq(LitemallCashSchedule::getDeviceNo, deviceNo)
                .eq(LitemallCashSchedule::getUserId, userId)
                .eq(LitemallCashSchedule::getShopId, shopId)
                .between(LitemallCashSchedule::getPayTime,LocalDate.now().atStartOfDay(), LocalDateTime.of(LocalDate.now(), LocalTime.MAX).withNano(0)));
        //统计今日POS现金交易额
        //订单金额
        BigDecimal orderCash = cashSchedules.stream().map(LitemallCashSchedule::getOrderCash).reduce(BigDecimal.ZERO, BigDecimal::add); // 获取每个订单的 orderCash 属性.reduce(BigDecimal.ZERO, BigDecimal::add);
        //找零金额
        BigDecimal change = cashSchedules.stream().map(LitemallCashSchedule::getChange).reduce(BigDecimal.ZERO, BigDecimal::add);

        //收取金额
        BigDecimal receiveCash = cashSchedules.stream().map(LitemallCashSchedule::getReceiveCash).reduce(BigDecimal.ZERO, BigDecimal::add);
        //退款金额
        BigDecimal refundCash = cashSchedules.stream().map(LitemallCashSchedule::getRefundCash).reduce(BigDecimal.ZERO, BigDecimal::add);

        WebPosGetOffVO posGetOffVO = WebPosGetOffVO.builder()
                .orderCash(orderCash)
                .change(change)
                .actualCash(orderCash.subtract(refundCash))
                .receiveCash(receiveCash)
                .refundCash(refundCash)
                .lastCheck(LocalDate.now().atStartOfDay())
                .build();
        return ResponseUtil.ok(posGetOffVO);
    }

    public ResponseUtil.Response noon(Integer userId, Integer shopId, String deviceNo) {
        if(userId==null){
            return ResponseUtil.badArgument();
        }
        //获取当前门店 当前店员 距离上一次日中结算的时间
        List<LitemallCashSettlement> litemallCashSettlements = cashSettlementService.list(Wrappers.lambdaQuery(LitemallCashSettlement.class)
                .eq(LitemallCashSettlement::getUserId, userId)
                .eq(LitemallCashSettlement::getDeviceNo, deviceNo)
                .eq(LitemallCashSettlement::getShopId, shopId)
                .eq(LitemallCashSettlement::getType,1)
                .between(LitemallCashSettlement::getAddTime,
                        LocalDate.now().atStartOfDay(),
                        LocalDateTime.now())
                .orderByDesc(LitemallCashSettlement::getAddTime));
        //当前设备 当前门店 当前店员 距离上一次日中结算
        LocalDateTime lastCheck= CollUtil.isNotEmpty(litemallCashSettlements)?litemallCashSettlements.get(0).getAddTime(): LocalDate.now().atStartOfDay();

        //当前设备 当天 当前门店 当前店员
        List<LitemallCashSchedule> cashSchedules = cashScheduleService.list(Wrappers.lambdaQuery(LitemallCashSchedule.class)
                .eq(LitemallCashSchedule::getDeviceNo, deviceNo)
                .eq(LitemallCashSchedule::getUserId, userId)
                .eq(LitemallCashSchedule::getShopId, shopId)
                .between(LitemallCashSchedule::getPayTime,
                        lastCheck,
                        LocalDateTime.now()));

        //统计今日POS现金交易额
        //订单金额
        BigDecimal orderCash = cashSchedules.stream().map(LitemallCashSchedule::getOrderCash).reduce(BigDecimal.ZERO, BigDecimal::add); // 获取每个订单的 orderCash 属性.reduce(BigDecimal.ZERO, BigDecimal::add);
        //找零金额
        BigDecimal change = cashSchedules.stream().map(LitemallCashSchedule::getChange).reduce(BigDecimal.ZERO, BigDecimal::add);

        //收取金额
        BigDecimal receiveCash = cashSchedules.stream().map(LitemallCashSchedule::getReceiveCash).reduce(BigDecimal.ZERO, BigDecimal::add);
        //退款金额
        BigDecimal refundCash = cashSchedules.stream().map(LitemallCashSchedule::getRefundCash).reduce(BigDecimal.ZERO, BigDecimal::add);

        WebPosGetOffVO posGetOffVO = WebPosGetOffVO.builder()
                .orderCash(orderCash)
                .change(change)
                .actualCash(orderCash.subtract(refundCash))
                .receiveCash(receiveCash)
                .refundCash(refundCash)
                .lastCheck(lastCheck)
                .build();
        return ResponseUtil.ok(posGetOffVO);
    }
}
